package ch.jhc.sevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import ch.jhc.Global;
import ch.jhc.db.UserDao;

/**
 * Servlet implementation class CheckServlet
 */
@WebServlet("/check.do")
public class CheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		//TODO: 到数据库查找该用户名是否被占用。
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		boolean isExists = false;
		try {
			isExists = UserDao.exists(runner, username);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (isExists) {
			out.println("{\"ok\":0}");
		}else {
			out.println("{\"ok\":1}");
		}
	}

}
